import {
  categoryGet,
  categoryPost,
  coursePost,
  coursePut,
  ICateParams,
  ICourseType,
} from "@/api/course";
import ImgUpload from "@/components/ImgUpload";
import RichEditor from "@/components/RichEditor";
import { Button, Form, Input, Select, Switch, Cascader } from "antd";
import TextArea from "antd/es/input/TextArea";
import React, { useEffect, useState, Dispatch, SetStateAction } from "react";
import { useLocation } from "react-router-dom";
import qs from "query-string";
const { Option } = Select;

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};

const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};
const CourseEdit: React.FC = (props) => {
  const [form] = Form.useForm();
  const [cateList, setCateList] = useState<ICateParams[]>([]);
  const location = useLocation();
  useEffect(() => {
    // 查询分类
    categoryGet({}).then((res) => {
      let { results } = res.data;
      let arr = results.filter((item: ICateParams) => item.fatherId == "0-0");
      arr.forEach((item: ICateParams) => {
        item.children = results.filter(
          (itm: ICateParams) => item.objectId == itm.fatherId
        );
      });
      setCateList(arr);
    });

    // 初始化表单数据
    console.log(location);
    let initData = qs.parse(location.search, { parseBooleans: true });
    form.setFieldsValue(initData);
  }, []);

  const onFinish = (values: ICourseType) => {
    values.catelv1 = values.category[0];
    values.catelv2 = values.category[1];
    console.log(values);
    let { objectId } = qs.parse(location.search);
    coursePut(objectId as string, values).then((res) => {
      console.log(res);
    });
  };

  const onReset = () => {
    form.resetFields();
  };
  return (
    <Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
      <Form.Item name="name" label="课程名称" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="info" label="课程简介" rules={[{ required: true }]}>
        <TextArea />
      </Form.Item>
      <Form.Item
        name="isvip"
        label="是否VIP"
        valuePropName="checked"
        rules={[{ required: true }]}
      >
        <Switch />
      </Form.Item>
      <Form.Item name="category" label="归属分类" rules={[{ required: true }]}>
        <Cascader
          fieldNames={{ label: "cateName", value: "objectId" }}
          options={cateList}
          placeholder="请选择归属分类"
        />
      </Form.Item>
      <Form.Item name="poster" label="课程封面" rules={[{ required: true }]}>
        <ImgUpload />
      </Form.Item>
      <Form.Item name="desc" label="课程详情" rules={[{ required: true }]}>
        <RichEditor />
      </Form.Item>

      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit">
          修改
        </Button>
        <Button htmlType="button" onClick={onReset}>
          重置
        </Button>
      </Form.Item>
    </Form>
  );
};

export default CourseEdit;
